<template>
  <div>
    <!-- 新增优惠券按钮 -->
    <el-button type="primary" @click="showAddDialog">新增优惠券</el-button>
    <!-- 筛选区域 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-select v-model="selectedDiscountType" placeholder="优惠券类型筛选">
          <el-option
              v-for="type in discountTypeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
          />
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-select v-model="selectedStatus" placeholder="优惠券状态筛选">
          <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
          />
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-input v-model="searchName" placeholder="输入优惠券名称点击搜索" clearable />
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="searchCoupons">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-col>
    </el-row>
    <!-- 优惠券表格展示区域 -->
    <el-table :data="filteredCoupons" border class="coupon-table" style="width: 100%">
      <el-table-column prop="name" label="优惠券名称" />
      <el-table-column label="折扣类型">
        <template #default="scope">
          {{ getDiscountTypeLabel(scope.row.discount_type) }}
        </template>
      </el-table-column>
      <el-table-column label="折扣值">
        <template #default="scope">
          {{ getDiscountValue(scope.row.discount_type, scope.row.discount_value) }}
        </template>
      </el-table-column>
      <el-table-column label="使用门槛">
        <template #default="scope">
          {{ getThresholdAmount(scope.row.threshold_amount) }}
        </template>
      </el-table-column>
      <el-table-column label="获取方式">
        <template #default="scope">
          {{ getObtainWayLabel(scope.row.obtain_way) }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="scope">
          {{ getStatusLabel(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="发放数量" prop="total_num" />
      <el-table-column label="用户限领数量" prop="user_limit" />
      <el-table-column label="已领取数量" prop="used_num" />
      <el-table-column label="有效期开始时间" prop="term_begin_time" />
      <el-table-column label="有效期结束时间" prop="term_end_time" />
      <el-table-column label="积分" prop="point" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="editCoupon(scope.row)">修改</el-button>
          <el-button type="text" @click="viewExchangeCode(scope.row)">查看兑换码</el-button>
          <el-button type="text" @click="deleteCoupon(scope.row)">删除</el-button>
          <el-button type="text" @click="distributeCoupon(scope.row)">发放</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
    />
    <!-- 修改优惠券的弹窗 -->
    <el-dialog title="修改优惠券" v-model="editDialogVisible" @close="closeEditDialog">
      <el-form :model="editCouponForm" label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="editCouponForm.name" />
        </el-form-item>
        <el-form-item label="折扣类型" prop="discount_type">
          <el-select v-model="editCouponForm.discount_type" @change="handleDiscountTypeChange">
            <el-option
                v-for="type in discountTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="折扣值" prop="discount_value">
          <el-input v-model.number="editCouponForm.discount_value"
                    :min="0"
                    :max="10"
                    step="0.1"
                    placeholder="请输入折扣值（0 - 10）" />
        </el-form-item>
        <el-form-item label="使用门槛" prop="threshold_amount">
          <el-input v-model.number="editCouponForm.threshold_amount"
                    :disabled="editCouponForm.discount_type === 3"
                    placeholder="请输入使用门槛金额" />
        </el-form-item>
        <el-form-item label="获取方式" prop="obtain_way">
          <el-select v-model="editCouponForm.obtain_way" disabled>
            <el-option
                v-for="way in obtainWayOptions"
                :key="way.value"
                :label="way.label"
                :value="way.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editCouponForm.status" placeholder="请选择状态">
            <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发放数量" prop="total_num">
          <el-input v-model.number="editCouponForm.total_num" placeholder="请输入发放数量" />
        </el-form-item>
        <el-form-item label="用户限领数量" prop="user_limit">
          <el-input v-model.number="editCouponForm.user_limit" placeholder="请输入用户限领数量" />
        </el-form-item>
        <el-form-item label="已领取数量" prop="used_num">
          <el-input v-model.number="editCouponForm.used_num" placeholder="请输入已领取数量" />
        </el-form-item>
        <el-form-item label="有效期开始时间" prop="term_begin_time">
          <el-date-picker v-model="editCouponForm.term_begin_time" type="datetime" placeholder="请选择有效期开始时间" />
        </el-form-item>
        <el-form-item label="有效期结束时间" prop="term_end_time">
          <el-date-picker v-model="editCouponForm.term_end_time" type="datetime" placeholder="请选择有效期结束时间" />
        </el-form-item>
        <el-form-item label="积分" prop="point">
          <el-input v-model.number="editCouponForm.point"
                    :disabled="editCouponForm.obtain_way === 2"
                    placeholder="请输入积分" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新增优惠券的弹窗 -->
    <el-dialog title="新增优惠券" v-model="addDialogVisible" @close="closeAddDialog">
      <el-form :model="addCouponForm" label-width="120px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="addCouponForm.name" />
        </el-form-item>
        <el-form-item label="折扣类型" prop="discount_type">
          <el-select v-model="addCouponForm.discount_type" @change="handleAddDiscountTypeChange">
            <el-option
                v-for="type in discountTypeOptions"
                :key="type.value"
                :label="type.label"
                :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="折扣值" prop="discount_value">
          <el-input v-model.number="addCouponForm.discount_value"
                    :min="0"
                    :max="10"
                    step="0.1"
                    placeholder="请输入折扣值（0 - 10）" />
        </el-form-item>
        <el-form-item label="使用门槛" prop="threshold_amount">
          <el-input v-model.number="addCouponForm.threshold_amount"
                    :disabled="addCouponForm.discount_type === 3"
                    placeholder="请输入使用门槛金额" />
        </el-form-item>
        <el-form-item label="获取方式" prop="obtain_way">
          <el-select v-model="addCouponForm.obtain_way" @change="handleAddObtainWayChange">
            <el-option
                v-for="way in obtainWayOptions"
                :key="way.value"
                :label="way.label"
                :value="way.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addCouponForm.status" disabled>
            <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发放数量" prop="total_num">
          <el-input v-model.number="addCouponForm.total_num" placeholder="请输入发放数量" />
        </el-form-item>
        <el-form-item label="用户限领数量" prop="user_limit">
          <el-input v-model.number="addCouponForm.user_limit" placeholder="请输入用户限领数量" />
        </el-form-item>
<!--        <el-form-item label="已领取数量" prop="used_num">-->
<!--          <el-input v-model.number="addCouponForm.used_num" placeholder="请输入已领取数量" />-->
<!--        </el-form-item>-->
        <el-form-item label="有效期开始时间" prop="term_begin_time">
          <el-date-picker v-model="addCouponForm.term_begin_time" type="datetime" placeholder="请选择有效期开始时间" />
        </el-form-item>
        <el-form-item label="有效期结束时间" prop="term_end_time">
          <el-date-picker v-model="addCouponForm.term_end_time" type="datetime" placeholder="请选择有效期结束时间" />
        </el-form-item>
        <el-form-item label="积分" prop="point">
          <el-input v-model.number="addCouponForm.point"
                    :disabled="addCouponForm.obtain_way === 2"
                    placeholder="请输入积分" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import moment from'moment';
import { addCoupon, addYhCode } from "@/api/coupon.js"; // 假设你的接口文件名为coupons.js，引入新增优惠券和新增兑换码的接口
import {getYhCouponsList, updateYhCoupon} from "@/api/coupon"; // 引入获取优惠券列表的接口

// 折扣类型选项
const discountTypeOptions = [
  { label: '每满减', value: 1 },
  { label: '折扣', value: 2 },
  { label: '无门槛', value: 3 }
];
// 状态选项
const statusOptions = [
  { label: '待发放', value: 1 },
  { label: '已发放', value: 2 }
];
// 获取方式选项
const obtainWayOptions = [
  { label: '手动领取', value: 1 },
  { label: '兑换码', value: 2 }
];

// 筛选相关的响应式数据
const selectedDiscountType = ref('');
const selectedStatus = ref('');
const searchName = ref('');

// 优惠券列表数据
const coupons = ref([]);
// 过滤后的优惠券列表数据
const filteredCoupons = computed(() => {
  let result = coupons.value;
  if (selectedDiscountType.value) {
    result = result.filter(coupon => coupon.discount_type === parseInt(selectedDiscountType.value));
  }
  if (selectedStatus.value) {
    result = result.filter(coupon => coupon.status === parseInt(selectedStatus.value));
  }
  if (searchName.value) {
    result = result.filter(coupon => coupon.name.includes(searchName.value));
  }
  return result;
});

// 当前页码
const currentPage = ref(1);
// 每页显示数量
const pageSize = ref(10);
// 总记录数
const total = ref(0);

// 控制修改优惠券弹窗的显示隐藏
const editDialogVisible = ref(false);
// 修改优惠券表单数据
const editCouponForm = ref({});

// 控制新增优惠券弹窗的显示隐藏
const addDialogVisible = ref(false);
// 新增优惠券表单数据
const addCouponForm = ref({});

// 搜索优惠券方法
const searchCoupons = () => {
  // 已经通过computed属性filteredCoupons自动过滤，无需额外操作
  total.value = filteredCoupons.value.length;
};

// 重置筛选条件方法
const resetFilters = () => {
  selectedDiscountType.value = '';
  selectedStatus.value = '';
  searchName.value = '';
  currentPage.value = 1;
  total.value = coupons.value.length;
};

// 切换页码时的处理方法
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 根据不同折扣类型返回对应文本描述的方法
const getDiscountTypeLabel = (type) => {
  const typeMap = {
    1: '每满减',
    2: '折扣',
    3: '无门槛'
  };
  return typeMap[type] || '';
};

const getDiscountValue = (type, value) => {
  if (type === 1) {
    return `满减${value}元`;
  } else if (type === 2) {
    return `${value}折`;
  }
  return value;
};

const getThresholdAmount = (amount) => {
  return amount === 0? '无门槛' : `最低消费${amount}元`;
};

const getObtainWayLabel = (way) => {
  return way === 1? '手动领取' : '兑换码';
};

const getStatusLabel = (status) => {
  return status === 1? '待发放' : '已发放';
};

// 编辑优惠券方法，弹出修改弹窗并填充表单数据
const editCoupon = (coupon) => {
  editDialogVisible.value = true;
  // 深拷贝原优惠券数据到表单数据，避免直接修改原数据
  editCouponForm.value = JSON.parse(JSON.stringify(coupon));
};

// 关闭修改弹窗时重置表单数据
const closeEditDialog = () => {
  editCouponForm.value = {};
};

// 处理修改优惠券中折扣类型改变时相关字段状态变化的方法
const handleDiscountTypeChange = () => {
  const discountType = editCouponForm.value.discount_type;
  if (discountType === 3) {
    editCouponForm.value.threshold_amount = 0;
  }
};

// 在确认修改前，对日期时间进行格式化处理的方法
const formatDateTimeBeforeSubmit = () => {
  if (editCouponForm.value.term_begin_time) {
    editCouponForm.value.term_begin_time = moment(editCouponForm.value.term_begin_time).format('YYYY-MM-DD HH:mm:ss');
  }
  if (editCouponForm.value.term_end_time) {
    editCouponForm.value.term_end_time = moment(editCouponForm.value.term_end_time).format('YYYY-MM-DD HH:mm:ss');
  }
};

// 确认修改优惠券的方法，调用接口更新数据
const confirmEdit = async () => {
  try {
    // 先格式化日期时间
    formatDateTimeBeforeSubmit();
    const response = await updateYhCoupon(editCouponForm.value);
    if (response.code === 1) {
      ElMessage.success('优惠券修改成功');
      editDialogVisible.value = false;
      // 重新获取优惠券列表数据，刷新页面显示
      await fetchCouponsList();
    } else {
      ElMessage.error('优惠券修改失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('修改优惠券出现错误，请稍后重试');
  }
};

// 显示新增优惠券弹窗的方法
const showAddDialog = () => {
  addDialogVisible.value = true;
  addCouponForm.value = {}; // 初始化表单数据
  addCouponForm.value.status = 1;
};

// 关闭新增优惠券弹窗时重置表单数据
const closeAddDialog = () => {
  addCouponForm.value = {};
};

// 处理新增优惠券中折扣类型改变时的相关字段状态变化
const handleAddDiscountTypeChange = () => {
  const discountType = addCouponForm.value.discount_type;
  if (discountType === 3) {
    addCouponForm.value.threshold_amount = 0;
  }
};

// 处理新增优惠券中获取方式改变时的积分字段状态变化
const handleAddObtainWayChange = () => {
  const obtainWay = addCouponForm.value.obtain_way;
  if (obtainWay === 2) {
    addCouponForm.value.point = 0;
  }
};

// 确认新增优惠券的方法
const confirmAdd = async () => {
  try {
    // 先格式化日期时间
    if (addCouponForm.value.term_begin_time) {
      addCouponForm.value.term_begin_time = moment(addCouponForm.value.term_begin_time).format('YYYY-MM-DD HH:mm:ss');
    }
    if (addCouponForm.value.term_end_time) {
      addCouponForm.value.term_end_time = moment(addCouponForm.value.term_end_time).format('YYYY-MM-DD HH:mm:ss');
    }
    const response = await addCoupon(addCouponForm.value);
    if (response.code === 1) {
      ElMessage.success('优惠券新增成功');
      addDialogVisible.value = false;
      if (addCouponForm.value.obtain_way === 2) {
        // 如果是兑换码获取方式的优惠券，获取刚添加的优惠券的id（假设coupons.value是已获取的优惠券列表数据）
        // 重新获取优惠券列表数据，刷新页面显示
        await fetchCouponsList();
        const lastCouponId = coupons.value.length > 0? coupons.value[coupons.value.length - 1].id : null;

        if (lastCouponId) {
          const yhCodeData = {
            code: '', // 这里你需要根据实际逻辑生成或获取兑换码值，此处先留空
            status: 1,
            user_id: 0,
            coupon_id: lastCouponId
          };
          const codeResponse = await addYhCode(yhCodeData);
          if (codeResponse.code === 1) {
            ElMessage.success('兑换码记录添加成功');
          } else {
            ElMessage.error('兑换码记录添加失败：' + codeResponse.msg);
          }
        }
      }
      // 重新获取优惠券列表数据，刷新页面显示
      await fetchCouponsList();
    } else {
      ElMessage.error('优惠券新增失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('新增优惠券出现错误，请稍后重试');
  }
};

// 操作按钮对应的其他方法（暂时只做提示，功能未实际实现）
const viewExchangeCode = (coupon) => {
  ElMessage.info(`查看优惠券${coupon.name}的兑换码`);
};

const deleteCoupon = (coupon) => {
  ElMessage.info(`删除优惠券：${coupon.name}`);
};

const distributeCoupon = (coupon) => {
  ElMessage.info(`发放优惠券：${coupon.name}`);
};


// 封装获取优惠券列表数据的方法
const fetchCouponsList = async () => {
  try {
    const data = await getYhCouponsList();
    if (data.code === 1) {
      coupons.value = data.data;
      total.value = coupons.value.length;
    }
  } catch (error) {
    ElMessage.error('加载优惠券列表失败');
  }
};

// 页面加载时获取所有优惠券，调用封装的方法
onMounted(() => {
  fetchCouponsList();
});
</script>

<style scoped>
.coupon-table.el-table__header {
  background-color: #f5f7fa;
}
.coupon-table.el-table__row {
  height: 50px;
}
.coupon-table.el-table td,
.coupon-table.el-table th {
  text-align: center;
}
.coupon-table.el-table__body-wrapper {
  border: 1px solid #e4e7ed;
}
.coupon-table.el-button {
  margin-right: 10px;
}
</style>